import React from 'react';
import { Form, Col, Button, Alert, Popconfirm, Modal, Drawer } from 'antd';
import QuickTool from '@/utils/Engineering/QuickTool';
import ApiTubro from '@/utils/Engineering/ApiTubro';
import ETable from '@/utils/Engineering/ETable';
import { withRouter } from 'react-router-dom';
import { openModalVisible, deepClone2, commonPagination, matrixFilter } from '@/utils/utils';
import SearchPart from './components/search-part';
import PopupPart from './components/popup-part';
import { fieldList, apiPath, pagination, popupForm } from './private.config.data';

import operateMode from './operate.mode';

class ViewSetting extends React.Component {
  pagination: any;
  tableInsideOperateRender: any;
  PopupPartTarget: any;
  state: any;
  props: any;

  constructor(props: any) {
    super(props);
    this.pagination = deepClone2(commonPagination) || deepClone2(pagination);
    this.state = {
      midTarget: {},
      unquickable: true,
      columns: [],
      dataSource: [],
      allFieldTarget: {},
      searchDataDict: {},
    };
    operateMode.bind(this)();
    console.log(
      this.props.location.pathname,
      '(this.props.loaction, this.props.loaction.pathname)',
    );
  }
  componentDidMount() {
    this.getColumnsRender({});
    this.getDatasource({});
  }

  //todo kim-stamp  getDerivedStateFromProps 从父组件获取派生状态
  // static getDerivedStateFromProps(nextPorps: any, prevState: any) {
  //   if (nextPorps.allFieldToValueObj != prevState.allFieldToValueObj) {
  //     return {
  //       allFieldToValueObj: nextPorps.allFieldToValueObj,
  //     }
  //   }
  //   return null
  // }

  componentWillReceiveProps(nextPorps: any) {
    if (nextPorps.allFieldToValueObj != this.state.allFieldToValueObj) {
      this.handleSearchToData(nextPorps.allFieldToValueObj);
    }
  }

  getColumnsRender({ setState = true }: { setState?: boolean }) {
    const self: any = this;
    let columnsList: Array<any> = [];
    fieldList
      // .sort((a:any, b:any) => a.sort - b.sort)
      .map((item: any) => {
        if (item.form_type) {
          item.render = (text: any, record: any, index: number) =>
            QuickTool[item.form_type + 'Edit'].bind(self)({
              columnItem: item,
              field: item.dataIndex_or_field,
              list: item.list,
              text,
              record,
              index,
            });
        }
        columnsList.push({
          title: item.title_or_label,
          dataIndex: item.dataIndex_or_field,
          key: item.dataIndex_or_field,
          width: item.width,
          render: item.render ? item.render : (text: any) => text,
          fixed: item.fixed ? item.fixed : false,
          ellipsis: item.ellipsis ? item.ellipsis : true,
          sorter: item.sorter ? item.sorter : false,
        });
      });
    if (this.tableInsideOperateRender) {
      columnsList.push(this.tableInsideOperateRender());
    }
    setState ? this.setState({ columns: columnsList }) : (this.state.columns = columnsList);
  }

  getDatasource({
    __sent_data,
    pursueId,
  }: {
    __sent_data?: any;
    pursueId?: any;
    setState?: boolean;
  }) {
    ApiTubro.getDatasource.bind(this)(apiPath.getDatasourceURL, {
      options: {
        method: 'POST',
        body: JSON.stringify(__sent_data || []),
        params: this.pagination,
      },
      extraData: { pursueId },
      // termina: "getDataAfter"
    });
  }

  // 「通用隐藏」废
  handleCurrencyInvisible = (e: any, value: any) => {
    const namespance = e.props.namespance;
    this.setState({ [namespance]: value });
  };
  // 「通用显示」废
  handleCurrencyVisible = (e: any, value: any) => {
    const namespance = e.props.namespance;
    this.setState({ [namespance]: value });
  };

  //拿到搜索面板提交的搜索参数 去后台获取搜索的数据
  handleSearchToData(value: any) {
    this.state.searchDataDict = value;
    let searchDataList: any[] = [];
    searchDataList;
    for (let [k, v] of Object.entries(value)) {
      if (v) {
        searchDataList.push({ key: k, value: v });
      }
    }
    this.pagination = deepClone2(pagination);
    this.state.searchDataList = searchDataList;
    this.getDatasource({ __sent_data: searchDataList });
  }

  render() {
    const { allFieldToValueObj } = this.props;
    const {
      pagination,
      selectedRowKeys,
      midTarget,
      unquickable,
      columns,
      dataSource,
      allFieldTarget,
      searchDataDict,
    } = this.state;

    const getPopupForm = () => {
      if (popupForm.open_type == 'Modal') {
        return (
          <Modal
            title={midTarget['modal_visible__title'] || '查看表单数据'}
            width={matrixFilter(popupForm.width)}
            visible={midTarget.modal_visible}
            // visible={midTarget.modal_visible|| true}
            onCancel={() => {
              openModalVisible({
                selfTarget: this,
                visibleName: 'modal_visible',
                isVisible: false,
              });
              this.setState(({ midTarget }: { midTarget: any }) => ({ midTarget }));
            }}
            onOk={e => {
              this.handleModalSubmit(e);
            }}
            // centered
          >
            <PopupPart
              wrappedComponentRef={(getTarget: any) => (this.PopupPartTarget = getTarget)}
              allFieldToValueObj={allFieldTarget}
            ></PopupPart>
          </Modal>
        );
      } else if (popupForm.open_type == 'Drawer') {
        return (
          <Drawer
            title={midTarget['modal_visible__title'] || '查看表单数据'}
            width={matrixFilter(popupForm.width)}
            visible={midTarget.modal_visible}
            onClose={() => {
              openModalVisible({
                selfTarget: this,
                visibleName: 'modal_visible',
                isVisible: false,
              });
              this.setState(({ midTarget }: { midTarget: any }) => ({ midTarget }));
            }}
          >
            <PopupPart
              wrappedComponentRef={(getTarget: any) => (this.PopupPartTarget = getTarget)}
              allFieldToValueObj={allFieldTarget}
            ></PopupPart>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <span>
                <Button type="primary" onClick={e => this.handleModalSubmit(e)}>
                  确定
                </Button>
                <Button
                  style={{ marginLeft: 10 }}
                  onClick={() => {
                    openModalVisible({
                      selfTarget: this,
                      visibleName: 'modal_visible',
                      isVisible: false,
                    });
                    this.setState(({ midTarget }: { midTarget: any }) => ({ midTarget }));
                  }}
                >
                  取消
                </Button>
              </span>
            </div>
          </Drawer>
        );
      } else {
        return null;
      }
    };

    return (
      <>
        <SearchPart
          onSubmit={(value: any) => this.handleSearchToData(value)}
          allFieldToValueObj={{ ...allFieldToValueObj, ...searchDataDict }}
        ></SearchPart>
        <Col span={24} style={{ marginBottom: 10 }}>
          {unquickable == true ? (
            <Button
              type="primary"
              onClick={e => this.handleQuickEdit(e, true)}
              style={{ marginRight: 10 }}
            >
              全部编辑
            </Button>
          ) : (
            <Button
              type="primary"
              ghost
              onClick={e => this.handleQuickEdit(e, false)}
              style={{ marginRight: 10 }}
            >
              关闭编辑
            </Button>
          )}

          <Button
            disabled={unquickable == true ? true : false}
            type={unquickable == true ? 'dashed' : 'primary'}
            ghost={unquickable == true ? true : false}
            style={{ marginRight: 10 }}
          >
            批量修改
          </Button>

          <Popconfirm
            placement="left"
            title={'你删除的数据可不止一条，请谨慎操作,不要到头来哭都来不及,确定要删除吗？'}
            // onConfirm={}
            okText="确定"
            cancelText="取消"
          >
            <Button
              disabled={selectedRowKeys ? (selectedRowKeys.length > 0 ? false : true) : true}
              type={selectedRowKeys && selectedRowKeys.length > 0 ? 'danger' : 'dashed'}
              ghost={selectedRowKeys && selectedRowKeys.length > 0 ? true : false}
              style={{ marginRight: 10 }}
            >
              批量删除
            </Button>
          </Popconfirm>
        </Col>

        <Col span={24} style={{ marginBottom: 10 }}>
          <Alert
            showIcon
            message={`选中总数共 ${(selectedRowKeys && selectedRowKeys.length) || 0} 项`}
            type="info"
            closable
            description=""
          />
        </Col>

        <Col span={24}>
          <ETable
            columns={columns}
            dataSource={dataSource}
            rowSelection="checkbox"
            updateSelectedItem={QuickTool.updateSelectedItem.bind(this)}
            pagination={pagination}
            size="middle"
            selectedRowKeys={selectedRowKeys}
            letterPoint={this}
          ></ETable>
        </Col>

        {getPopupForm()}
      </>
    );
  }
  handleQuickEdit(e: E, arg1: boolean): void {
    throw new Error('Method not implemented.');
  }
  handleModalSubmit(e: React.MouseEvent<HTMLElement, MouseEvent>) {
    throw new Error('Method not implemented.');
  }
}

export default withRouter(Form.create({ name: 'ViewSetting' })(ViewSetting));
